package com.example.budget3.months;

import java.util.Calendar;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.example.budget3.R;
import com.example.budget3.modify.AddTransaction;
import com.example.budget3.recurring.RecurringManager;
import com.example.budget3.settings.UserSettingActivity;
import com.example.budget3.util.DatabaseQueryHandler;
import com.example.budget3.util.UtilMethods;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceFragment;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

@SuppressLint("SimpleDateFormat")
public class MainActivity extends FragmentActivity implements
		ActionBar.OnNavigationListener {
	
	private ViewPager monthPager;
	private MonthPagerAdapter monthPagerAdapter;
	
	//result id for different activities launched from this activity
	private static final int RESULT_SETTINGS = 1;
	private static final int RESULT_ADD = 2;
	public static final int RESULT_EDIT = 3;
	public static final int RESULT_RECUR = 4;
	public static final int RESULT_EDIT_RECURRING = 5;
	
	//used to identify when the message is sent from a bill being due
	private static final int BILL_UPDATE_CHECK = 0;

	//the current month being shown on screen
	private int month;
	//represents the number of months
	private int numberOfMonths;
	private MonthSpinnerAdapter monthSpinnerAdapter;
	//check for bill updates and creating separate threads for them
	private ScheduledExecutorService billsUpdateService;
	private ScheduledFuture<?> billsUpdateSchedule;
	Handler billsUpdateHandler;
	private boolean ignoreFromRecreatingPagerAdapter = false;
	
	private class CheckBillUpdateRunnable implements Runnable {
		//sends message to check for bill update
		public void run() {
			Message msg;
			msg = Message.obtain();
			msg.what = BILL_UPDATE_CHECK;
			billsUpdateHandler.sendMessage(msg);
		}
	}
	
	private class BillsUpdateHandlerCallback implements Handler.Callback {
		//bill update message received, checks for any changes including bills
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case BILL_UPDATE_CHECK:
				checkForChanges(false);
				break;
			}
			return true;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (billsUpdateService != null) {
			billsUpdateService.shutdown();
			billsUpdateService = null;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		//checkForChanges();
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.month_pager_activity);
		

		billsUpdateHandler = new Handler(new BillsUpdateHandlerCallback());
		if (savedInstanceState != null) {
			month = savedInstanceState.getInt("month");
		} else {
			month = 0;
		}
		numberOfMonths = DatabaseQueryHandler.numberOfMonths(this, Calendar.getInstance());
		monthPagerAdapter = new MonthPagerAdapter(
				getSupportFragmentManager(), numberOfMonths, Calendar.getInstance());
		
		monthPager = (ViewPager) findViewById(R.id.month_detail_container);
		monthPager.setAdapter(monthPagerAdapter);
		monthPager.setOffscreenPageLimit(3);
		monthPager.setPageTransformer(true, new DepthPageTransformer());
		monthPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				month = arg0;
				setTitleInActionBar();
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {}

			@Override
			public void onPageScrollStateChanged(int arg0) {}
		});
		
		monthPager.setCurrentItem(month, true);
		createMonthSpinner();
		setTitleInActionBar();
		
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			SystemBarTintManager tintManager = new SystemBarTintManager(this);
			tintManager.setStatusBarTintEnabled(true);
			tintManager.setStatusBarTintResource(R.color.action_bar_hint);
		}
	}

	private void createMonthSpinner() {
		Calendar now = Calendar.getInstance();
		ActionBar mActionBar = getActionBar();
		if (numberOfMonths > 1) {
			mActionBar.setTitle("");
			mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
			monthSpinnerAdapter = new MonthSpinnerAdapter(this, now);
			mActionBar.setListNavigationCallbacks(monthSpinnerAdapter, this);
		} else {
			mActionBar.setNavigationMode(ActionBar.DISPLAY_SHOW_TITLE);
			mActionBar.setTitle(UtilMethods.getMonthName(now));
		}
	}
	
	private void setTitleInActionBar() {
		if (monthSpinnerAdapter != null) {
			//sets the month spinner to the correct date 
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.MONTH, -1 * month);
			monthSpinnerAdapter.setTime(cal.getTimeInMillis());
		}
	}

	public void changePage(int page) {
		monthPager.setCurrentItem(page, true);
		setTitleInActionBar();
		ActionBar mActionBar = getActionBar();
		mActionBar.setSelectedNavigationItem(3);
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		ActionBar mActionBar = getActionBar();
		mActionBar.setSelectedNavigationItem(3);
		if(ignoreFromRecreatingPagerAdapter){
			ignoreFromRecreatingPagerAdapter = false;
			return false;
		}
		if (itemPosition < 2) {
			month = itemPosition;
			monthPager.setCurrentItem(month, true);
			setTitleInActionBar();
		} else if (itemPosition == 2) {
			
			DialogFragment newFragment = new MonthDialogFragment();
			Bundle positionBundle = new Bundle();
			positionBundle.putInt("count", numberOfMonths);
			newFragment.setArguments(positionBundle);
			newFragment.show(getSupportFragmentManager(), "change");

		}
		
		return false;
	}
	
	public synchronized void checkForChanges(boolean removed) {
		if(!removed){
			ignoreFromRecreatingPagerAdapter = true;
			DatabaseQueryHandler.checkForBillsUpdate(this);
		}
		int newNumberOfMonths = DatabaseQueryHandler.numberOfMonths(this, Calendar.getInstance());
		month = monthPager.getCurrentItem();
		if(newNumberOfMonths != numberOfMonths){
			numberOfMonths = newNumberOfMonths;
			if (month > numberOfMonths) {
				month = numberOfMonths;
			}
			monthPagerAdapter.setCount(numberOfMonths);
			monthPagerAdapter.notifyDataSetChanged();
			monthPager.setAdapter(null);
			monthPager.setAdapter(monthPagerAdapter);
		}else{
			if(!removed){
				monthPagerAdapter.notifyDataSetChanged();
			}
			
		}
		createMonthSpinner();
		setTitleInActionBar();
		monthPager.setCurrentItem(month);
		long untilNext = DatabaseQueryHandler.nextBillOrHalfHour(this);
		
	
		if (billsUpdateService == null) {
			billsUpdateService = new ScheduledThreadPoolExecutor(1);
		}
		if (billsUpdateSchedule != null) {
			billsUpdateSchedule.cancel(false);
		}
	
		billsUpdateSchedule = billsUpdateService.schedule(new CheckBillUpdateRunnable(), untilNext,	TimeUnit.MILLISECONDS);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_add:
			Intent addIntent = new Intent(this, AddTransaction.class);
			startActivityForResult(addIntent, RESULT_ADD);
			break;
		case R.id.action_settings:
			Intent setting = new Intent(this, UserSettingActivity.class);
			startActivityForResult(setting, RESULT_SETTINGS);
			break;
		case R.id.manage_recurring:
			Intent manage = new Intent(this, RecurringManager.class);
			startActivityForResult(manage, RESULT_RECUR);
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		checkForChanges(false);
	}
	
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		savedInstanceState.putInt("month", monthPager.getCurrentItem());
		super.onSaveInstanceState(savedInstanceState);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.findItem(R.id.action_add);
		return super.onPrepareOptionsMenu(menu);
	}

	public static class SettingsFragment extends PreferenceFragment {
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			addPreferencesFromResource(R.xml.preferences);
		}
	}

}
